

// 验证内容
var strategies = {
	// 表单验证内容
	isNonEmpty: function(value, voids, errorMsg) {  // 验证是否必填 内容不能为空
		if(value === '' || value == voids) {
			return errorMsg
		}
	},
	isDefault: function(value, errorMsg){  // 是否为默认下拉选项
		if(value == $(this).attr('data-default')) {
			return errorMsg
		}
	},
	isMobile: function(value, errorMsg) {  // 验证手机格式
		if(value != '' && !/^((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8}$/.test(value)) {
			return errorMsg
		}
	},
	testEmail: function(value, errorMsg) {  // 验证邮箱格式
		if(value != '' && !/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(value)) {
			return errorMsg
		}
	},
	isCardNo: function(value, errorMsg) {  // 验证身份证格式
		if(value != '' && !/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/.test(value) ) {
			return errorMsg
		}
	},
	isQQ: function(value, errorMsg) {  // 验证qq格式
		if(value != '' && !/[1-9][0-9]{4,}/.test(value)) {
			return errorMsg
		}
	},
	isAgreement: function(value, errorMsg) {  // 验证协议是否勾选
		if(!$(this).is('.checked')) {
			return errorMsg
		}
	},
	e:''  // dom标记
}

// 定义Validator类
var Validator = function() {  
	this.cache = []
}

Validator.prototype.add = function(dom, rule, errorMsg) {	
	var ary = rule.split(':');
	this.cache.push(function() {
		var strategy = ary.shift();
		ary.unshift($(dom).val());
		ary.push(errorMsg);
		return strategies[ strategy ].apply($(dom), ary)
	})
}

Validator.prototype.start = function() {
	for (var i = 0,validatorFunc;validatorFunc = this.cache[i++];) {
		var msg = validatorFunc();
		if(msg) {
			return msg
		}
	}
}


var validataFunc = function(rule) {
	var validator = new Validator();
	// 添加校验规则
	for(var i = 0; i < rule.length; i++){
		if($(rule[i].dom).val != undefined){
			validator.add(rule[i].dom, rule[i].type, rule[i].msg);
		}
	}
	var errorMsg = validator.start();
	return errorMsg
}


var onSubmit = function (dom, extend) {
	strategies.e = dom;
	var rule = [
		$(dom + ' [name="school"]').length ? {dom:$(dom + ' [name="school"]'), type:'isDefault', msg:'请选择学校'} : '',
		$(dom + ' [name="grade"]').length ? {dom:$(dom + ' [name="grade"]'), type:'isDefault', msg:'请选择年级'} : '',
		$(dom + ' [name="YYYY"]').length ? {dom:$(dom + ' [name="YYYY"]'), type:'isDefault', msg:'请选择年份'} : '',
		$(dom + ' [name="MM"]').length ? {dom:$(dom + ' [name="MM"]'), type:'isDefault', msg:'请选择月份'} : '',
		$(dom + ' [name="DD"]').length ? {dom:$(dom + ' [name="DD"]'), type:'isDefault', msg:'请选择日期'} : '',
		{dom:$(dom + ' [name="custom"]'),type:'isNonEmpty:姓名', msg:'姓名不能为空'},
		{dom:$(dom + ' [name="phone"]'),type:'isNonEmpty:', msg:'手机格不能为空'}, 
		{dom:$(dom + ' [name="phone"]'),type:'isMobile', msg:'手机格式不正确'}, 
		$(dom + ' [name="id_card"]').length ? {dom:$(dom + ' [name="id_card"]'),type:'isCardNo', msg:'身份证格式不正确'} : '',
		$(dom + ' [name="email"]').length ? {dom:$(dom + ' [name="email"]'),type:'testEmail', msg:'邮箱格式不正确'} : '',
		$(dom + ' [name="qq"]').length ? {dom:$(dom + ' [name="qq"]'),type:'isQQ', msg:'qq格式不正确'}: ''
	];
	
	var errorMsg = validataFunc(removeEmptyArrayEle(rule));
	if (errorMsg) {
		alert(errorMsg);
		return false
	}
	var YYYY = getselect($(dom + ' [name="YYYY"]')) ? getselect($(dom + ' [name="YYYY"]')) + '-' : ''; //年
	var MM = getselect($(dom + ' [name="MM"]')) ? getselect($(dom + ' [name="MM"]')) + '-' : ''; //月
	var DD = getselect($(dom + ' [name="DD"]')); //日

	var id_card = $(dom + ' [name="id_card"]').val() || '';   // 身份证
	var grade = getselect($(dom + ' [name="grade"]')); // 年级
	var score = getselect($(dom + ' [name="score"]'));  // 分数
	var graduate_from = getselect($(dom + ' [name="graduate_from"]')); // 毕业院校
	var country = getselect($(dom + ' [name="country"]')); // 意向国家
	var city = getselect($(dom + ' [name="city"]')); // 城市   
	var birthplace = getselect($(dom + ' [name="birthplace"]')); // 籍贯
	var qq = $(dom + ' [name="qq"]').val() || ''; // qq
	var sex = getCheckSet($(dom + ' .checked [name="sex"]')) || getselect($(dom + ' [name="sex"]')) || ''; // 性别
	var degree = getCheckSet($(dom + ' .checked [name="degree"]')) || getselect($(dom + ' [name="degree"]')); // 学历
	var degree_state = getCheckSet($(dom + ' .checked [name="degree_state"]')) || getselect($(dom + ' [name="degree_state"]')); // 有无学位
	var birth_day = $(dom + ' [name="birthday"]').val() || YYYY + MM + DD || '';	  // 出生日期
	var working_years = getCheckSet($(dom + ' .checked [name="working_years"]')) || getselect($(dom + ' [name="working_years"]')); // 工作年限
	var parent_name = $(dom + ' [name="parent_name"]').val() || ''; // 家长姓名
	var parent_phone = $(dom + ' [name="parent_phone"]').val() || ''; // 家长电话 
	var wechat = $(dom + ' [name="wechat"]').val() || ''; // 微信
	var money = getselect($(dom + ' [name="money"]')); // 学费
	var other = $(dom + ' [name="other"]').val() || ''; // 问题描述
	var discount = getselect($(dom + ' [name="discount"]')); // 优惠、礼包
	var viaMsg = $(dom + ' [name="viaMsg"]').val() || ''; // 提交成功内容
	var marks = $(dom + ' [name="mark"]').val() || '' // 备注
	var age = getCheckSet($(dom + ' .checked [name="age"]')) || getselect($(dom + ' [name="age"]')); // 年龄
	var serves = getCheckSet($(dom + ' .checked [name="serves"]')) || getselect($(dom + ' [name="serves"]')); // 服务

	var markCnt = ( degree_state !='' ? '有无学位：'+ degree_state + '；' : '') + ( city !='' ? '所在城市：'+ city + '；' : '') + ( country !='' ? '意向国家：'+ country + '；' : '') + ( birthplace !='' ? '籍贯：'+ birthplace + '；' : '') + ( wechat!='' ? '微信：'+ wechat + '；' : '') + 
	 ( qq !='' ? 'qq：'+ qq + '；' : '') + ( id_card !='' ? '身份证：'+ id_card + '；' : '') + ( grade !='' ? '年级：'+ grade + '；' : '') + 
	 ( graduate_from !=''? '毕业院校：'+ graduate_from + '；' : '') + ( score !=''? '分数：'+ score + '；' : '') + ( money !='' ? '学费：' + money + '；' : '') + ( other != '' ? '问题描述：' + other + '；' : '') + 
	 ( degree !='' ? '学历：' + degree + '；' : '') + ( working_years !='' ? '工作年限：'+ working_years + '；' : '') + ( parent_name !='' ? '家长姓名：'+ parent_name + '；' : '') + ( parent_phone !='' ? '家长电话：'+ parent_phone + '；' : '') +
	 ( discount != '' ? '优惠：' + discount + '；' : '' ) + ( marks != '' ? '备注：' + marks + '；': '') +  ( age != '' ? '年龄：' + age + '；' : '' ) + ( serves != '' ? '服务：' + serves + '；': '');
	
	var data = {
		subflag: $(dom + ' [name="subflag"]').val() || '', // 来源页类型
		info: $(dom + ' [name="info"]').val() || '',  // 信息id
		subsite_id: $(dom + ' [name="subsite_id"]').val() || '',   // 分站id
		category: $(dom + ' [name="category"]').val() || '',   // 项目分类
		type: $(dom + ' [name="type"]').val() || '',    // 订单分类
		custom: $(dom + ' [name="custom"]').val(),  // 姓名
		phone: $(dom + ' [name="phone"]').val(),  // 电话
		content: $(dom + ' [name="content"]').val(),  // 标题
		birthday: birth_day,	  // 出生日期
		sex: sex, // 性别
		mark: markCnt,	  // 备注
		school: getselect($(dom + ' [name="school"]')) || '', // 学校
		email: $(dom + ' [name="email"]').val() || '',  // 邮箱
		address: $(dom + ' [name="address"]').val() || '',  // 地址
		project: getselect($(dom + ' [name="project"]')) || '', // 专业
		id: $(dom + ' [name="id"]').val() || ''  // 课程id
	}; 
	
	sieve(data);  // 去除空值；
	if(extend){
		// 有特殊条件判断
		submitForm(data, false);
	} else {
		// 无特殊判断条件
		submitForm(data, true, viaMsg);
	}
}

// ajax
var submitForm = function(params, asyncStart, alertMsg) {
	try{
		specialTips(strategies.e);
	} catch (e){
		alert(alertMsg);
	} 
	$.ajax({
		url: 'http://www.xue114.com/api/baoming/',
		type: 'post',
		data: params,
		dataType: 'json',
		headers: {
			Accept: 'application/json',
			"Content-Type": "application/x-www-form-urlencoded"
		},
		success: function(res) {
			if(res.status == 1) {
				window._agl && window._agl.push(['track', ['success', {t: 3}]]); // 百度推广 埋码
				if(!asyncStart){
					try{
						specialTips(strategies.e);
					} catch (e){
						alert(alertMsg);
					} 
				} else {
					alert(alertMsg);
				}
            } else {
				alert(res.info);
            }   
		}
	})
}

var sieve = function(data) {
	for (var key in data) {
		if (data[key] === '') {
			delete data[key];
		}
	}
}

$('.checkbox-item').click(function(){
	$(this).addClass('checked').siblings().removeClass('checked');
})

var getCheckSet = function(params){  // check 可多选
	var checkList = []
	for(var i = 0; i < params.length; i++){
		checkList.push($(params[i]).val()) ;
	}
	return checkList +''
}

var getselect = function(params){  // select Value
	var val = params.val() || '';
	var initVal = params.attr('data-default') || '';
	return initVal == '' ? val : val == initVal ? '' : val 
}
function removeEmptyArrayEle(arr){    
	for(var i = 0; i < arr.length; i++) {
		if(arr[i] == undefined || arr[i] == '') {
			arr.splice(i,1);
			i = i - 1; 
		}
	}
	return arr;
};
